<template>
  <div class="topSelect" @click.stop="closeTooltips">
    <div class="topSelectLabel">
      <div class="name">院 系</div>
    </div>
    <div class="topSelectList">
      <!-- 这个checkbox用于计算元素宽度 -->
      <div class="topSelectContainer" id="dis">
        <el-tooltip effect="light" placement="bottom" v-for="item,index in classList" :key="item.careerTagId"
          popper-class="depFilterTooptip">
          <div :class="{'topSelectItem':true,'topHasSelected':item.selectedNum||item.isShowTooltip}"
            @click.stop="handleTopSelectItemClick(item)">
            {{ item.depName }}
            <span v-show="item.selectedNum">·{{item.selectedNum}}</span>
          </div>
          <div slot="content" class="tooltipWrapper" @mouseleave.stop="closeTooltips">
            <div class="tooltipTop">
              {{item.depName}}
            </div>
            <div class="tooltipContent">
              <div class="secondCategory" v-show="item.children&&item.children.length">
                <div :class="{'secondCategoryItem':true,'secondHasSelected':secondItem.selectedNum}"
                  @click="handleSecondItemClick(secondItem)" v-for="secondItem,secondIndex in item.children"
                  :key="secondIndex">
                  {{secondItem.depName}} <span v-show="secondItem.selectedNum">·{{secondItem.selectedNum}}</span>
                </div>
              </div>
              <div class="thirdCategory">
                <div class="thirdCategoryItem" v-if="secondSelectedItem.children&&secondSelectedItem.children.length">
                  <div class="thirdCategoryItemTitle">{{secondSelectedItem.depName}}
                  </div>
                  <div class="thirdCategoryItemContent">
                    <el-checkbox-group v-model="selectedThirdCategory" @change="handleCheckedClassChange"
                      v-if="secondSelectedItem.children" :max="3">
                      <!-- 因为多选了以后depId和depName都要用，所以拼在一起，需要的时候要额外处理哦，下面有例子 -->
                      <el-checkbox :label="thirdItem.depId+','+thirdItem.depName"
                        v-for="thirdItem,thirdIndex in secondSelectedItem.children" :key="thirdIndex"
                        @change="handleThirdChange(item,secondSelectedItem,thirdItem)">{{thirdItem.depName}}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </div>
            </div>
            <div class="tooltipBottom">
              <span class="tooltipBottonLabel">已选 {{selectedThirdCategory.length}}/3: </span>
              <!-- 这里就是从selectedThirdCategory中分解depId和depName的例子 -->
              <el-tag closable class="tooltipBottonTag" v-for="tagItem,index in selectedThirdCategory" :key="index"
                @close="handleTagClose(tagItem,item)">{{tagItem.slice(tagItem.lastIndexOf(',')+1)}}</el-tag>
            </div>
          </div>
        </el-tooltip>
      </div>

      <div class="topSelectContainer" v-if="currentClassList.length">
        <el-tooltip v-model="item.isShowTooltip" manual effect="light" placement="bottom"
          v-for="item,index in currentClassList" :key="item.careerTagId" popper-class="depFilterTooptip">
          <div
            :class="{'topSelectItem':true,'topHasSelected':(!selectedClass||selectedClass.length==0)&&!(selectedThirdCategory.length)}"
            @click.stop="handleAllPositionClick()" v-if="item.careerTagId==0">
            {{ item.depName }}
          </div>
          <div :class="{'topSelectItem':true,'topHasSelected':item.selectedNum||item.isShowTooltip}"
            @click.stop="handleTopSelectItemClick(item)" v-else>
            {{ item.depName }}
            <span v-show="item.selectedNum">·{{item.selectedNum}}</span>
          </div>
          <div slot="content" class="tooltipWrapper" @mouseleave.stop="closeTooltips">
            <div class="tooltipTop">
              {{item.depName}}
            </div>
            <div class="tooltipContent">
              <div class="secondCategory" v-show="item.children&&item.children.length">
                <div :class="{'secondCategoryItem':true,'secondHasSelected':secondItem.selectedNum}"
                  @click="handleSecondItemClick(secondItem)" v-for="secondItem,secondIndex in item.children"
                  :key="secondIndex">
                  {{secondItem.depName}} <span v-show="secondItem.selectedNum">·{{secondItem.selectedNum}}</span>
                </div>
              </div>
              <div class="thirdCategory">
                <div class="thirdCategoryItem" v-if="secondSelectedItem.children&&secondSelectedItem.children.length">
                  <div class="thirdCategoryItemTitle">{{secondSelectedItem.depName}}
                  </div>
                  <div class="thirdCategoryItemContent">
                    <el-checkbox-group v-model="selectedThirdCategory" v-if="secondSelectedItem.children" :max="3"
                      @change="handleCheckedClassChange">
                      <!-- 因为多选了以后depId和depName都要用，所以拼在一起，需要的时候要额外处理哦，下面有例子 -->
                      <el-checkbox :label="thirdItem.depId+','+thirdItem.depName"
                        v-for="thirdItem,thirdIndex in secondSelectedItem.children" :key="thirdIndex"
                        @change="(e)=>{handleThirdChange(item,secondSelectedItem,thirdItem,e)}">{{thirdItem.allName||thirdItem.depName}}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </div>
            </div>
            <div class="tooltipBottom">
              <span class="tooltipBottonLabel">已选 <span style="color:#0B6EFF">{{selectedThirdCategory.length}}</span>/3:
              </span>
              <!-- 这里就是从selectedThirdCategory中分解depId和depName的例子 -->
              <el-tag closable class="tooltipBottonTag" v-for="tagItem,index in selectedThirdCategory" :key="index"
                @close="handleTagClose(tagItem,item)">{{tagItem.slice(tagItem.lastIndexOf(',')+1)}}</el-tag>
            </div>
          </div>
        </el-tooltip>
      </div>

      <div class="topSelectMore" v-if="btnShow" @click="partChange">
        <button v-if="part">更多<i class="el-icon-arrow-down"></i></button>
        <button v-else>收起<i class="el-icon-arrow-up"></i></button>
      </div>
    </div>
  </div>
</template>
<script>
import { positionTreeInterface } from "@/api/home.js";

export default {
  data() {
    return {
      classList: [],
      selectedClass: [],
      part: true,
      currentClassList: [],
      partData: [],
      btnShow: false,
      isIndeterminate: false,
      checkAll: true,
      selectedThirdCategory: [],
      secondSelectedItem: [],
    };
  },
  methods: {
    handleCheckedClassChange() {
      const idList = this.selectedThirdCategory.map((item) => {
        return {
          depId: item.slice(0, item.lastIndexOf(",")),
          depName: item.slice(item.lastIndexOf(",") + 1),
        };
      });
      this.$emit("selectedChecks", idList);
      this.saveSessionData();
    },

    // 选中之后要给父级加选中数目
    handleThirdChange(firstItem, secondItem, thirdItem, e) {
      // console.log(
      //   "firstItem,secondItem,thirdItem",
      //   firstItem,
      //   secondItem,
      //   thirdItem,
      //   e,
      //   this.selectedThirdCategory
      // );
      // //当选中学院下面的“全部”的时候，其他专业不让选
      // if (e && thirdItem.allName && this.selectedThirdCategory.length) {
      //   if (secondItem) {
      //     secondItem.disableMutiple = true;
      //   }
      // } else {
      //   if (secondItem) {
      //     secondItem.disableMutiple = false;
      //   }
      // }
      var firstSelectCount = 0;
      if (firstItem.children) {
        firstItem.children.forEach((secondItem) => {
          if (secondItem.children) {
            secondItem.selectedNum = this.getArraySelectCount(
              secondItem.children
            );
            firstSelectCount += secondItem.selectedNum;
          }
        });
      }
      firstItem.selectedNum = firstSelectCount;
    },
    //删除tag也要重新计算选中数目
    handleTagClose(val, firstItem) {
      this.selectedThirdCategory = this.selectedThirdCategory.filter((item) => {
        return item != val;
      });
      this.handleThirdChange(firstItem);
      this.handleCheckedClassChange();
    },
    getArraySelectCount(array) {
      var count = 0;
      array.forEach((item) => {
        if (
          this.selectedThirdCategory.indexOf(`${item.depId},${item.depName}`) !=
          -1
        ) {
          count += 1;
        }
      });
      return count;
    },
    handleSecondItemClick(secondItem) {
      this.secondSelectedItem = secondItem;
    },
    handleTopSelectItemClick(item) {
      if (item.isShowTooltip == true) return;
      if (item.selectedNum) {
        item.isShowTooltip = true;
        item.children.forEach((secondItem) => {
          if (secondItem.selectedNum) {
            this.secondSelectedItem = secondItem;
          }
        });
        return;
      }

      if (!this.secondSelectedItem.tagTitle) {
        this.secondSelectedItem = item.children ? item.children[0] : {};
      }
      this.currentClassList.forEach((item) => {
        item.isShowTooltip = false;
        item.selectedNum = 0;
        if (item.children) {
          item.children.forEach((_item) => {
            this.$set(_item, "selectedNum", 0);
          });
        }
      });
      this.selectedThirdCategory = [];
      if (!item.selectedNum && !this.selectedThirdCategory.length) {
        // this.$emit("selectedChecks", []);
      }
      this.$set(item, "isShowTooltip", true);
    },
    handleAllPositionClick() {
      this.currentClassList.forEach((item) => {
        item.isShowTooltip = false;
        item.selectedNum = 0;
        if (item.children) {
          item.children.forEach((_item) => {
            this.$set(_item, "selectedNum", 0);
          });
        }
      });
      this.selectedThirdCategory = [];
      this.$emit("selectedChecks", []);
    },
    closeTooltips() {
      //console.log("触发了closeTooltips");

      this.currentClassList.forEach((item) => {
        item.isShowTooltip = false;
      });
      this.secondSelectedItem = {};
    },
    getClassList(hasNoSessionClassList) {
      positionTreeInterface({
        // customerId: 1000,
      }).then((res) => {
        if (res.code == 200) {
          this.classList = res.data;

          this.classList.forEach((firstItem) => {
            if (firstItem.children) {
              firstItem.children.forEach((secondItem) => {
                if (secondItem.children) {
                  const obj = {
                    depName: firstItem.depName,
                    depId: 0,
                    allName: "全部",
                  };
                  const depId = secondItem.children
                    .map((thirdItem) => {
                      return thirdItem.depId;
                    })
                    .join(",");
                  obj.depId = depId;
                  secondItem.children.unshift(obj);
                }
              });
            }
          });
          this.classList.unshift({
            depName: "全部职业",
            careerTagId: 0,
          });
          if (hasNoSessionClassList) {
            //如果没有缓存的话要手动触发一下获取职位列表
            this.$emit("selectedChecks", []);
          }
          //获取数据后在渲染筛选类别列表
          this.filterListWidth();
        }
      });
    },
    partChange() {
      if (this.part) {
        this.part = false;
        this.currentClassList = this.classList;
      } else {
        //展开
        this.part = true;
        this.currentClassList = this.partData;
      }
    },
    filterListWidth() {
      setTimeout(() => {
        const dis = document.getElementById("dis");
        let wid1 = 0;
        let wid2 = 0;
        const el = document.getElementsByClassName("topSelectContainer")[0];
        const boxWidth = Number(
          window.getComputedStyle(el).width.replace("px", "")
        );

        try {
          dis.childNodes.forEach((item, idx) => {
            wid1 += item.clientWidth + 40;
            if (boxWidth < wid1 + 72) {
              wid2 += item.clientWidth + 40;
            }

            if (boxWidth >= wid2) {
              this.partData.push(this.classList[idx]);
              this.currentClassList = this.partData;
            } else {
              throw new Error();
            }
          });
        } catch {
        } finally {
          if (boxWidth >= wid2) {
            this.btnShow = false;
          } else {
            this.btnShow = true;
          }
          dis.className = "disn";
          let arr = [];
          for (let item of this.classList) {
            arr.push(item);
          }
          // this.selectedClass = arr;
        }
      }, 100);
    },
    saveSessionData() {
      //存的时候要把所以isShowTooltip关掉

      sessionStorage.setItem("classList", JSON.stringify(this.classList));

      sessionStorage.setItem(
        "selectedThirdCategory",
        JSON.stringify(this.selectedThirdCategory)
      );
    },
  },
  mounted() {
    const sessionClassList = sessionStorage.getItem("classList");
    const selectedThirdCategory = sessionStorage.getItem(
      "selectedThirdCategory"
    );
    const sessionClassListArray = JSON.parse(sessionClassList);
    if (sessionClassListArray && sessionClassListArray.length) {
      this.classList = sessionClassListArray.map((item) => {
        item.isShowTooltip = false;
        return item;
      });
      this.filterListWidth();
    } else {
      //console.log("123456");

      this.getClassList(true);
    }
    if (selectedThirdCategory && selectedThirdCategory.length) {
      this.selectedThirdCategory = JSON.parse(selectedThirdCategory);
      this.handleCheckedClassChange();
    }
  },
  beforeUnload() {
    this.saveSessionData();
  },
  beforeDestroy() {
    this.saveSessionData();
  },
  beforeUnmount() {
    this.saveSessionData();
  },
};
</script>
<style lang="scss" scoped>
.disn {
  display: none;
}
.topSelect {
  display: flex;
  margin: 14px 0;
  margin-top: 12px;
  position: sticky;
  top: 60px;
  margin: 0 14px 12px;
  padding: 12px 28px;
  padding-right: 70px;
  padding-bottom: 10px;
  background: linear-gradient(180deg, #d0e3ff 0%, #f1f4f9 50%);
  border-radius: 16px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.26);
  z-index: 8;
  width: calc(100% - 28px);

  .topSelectLabel {
    flex: 0 0 80px;
    font-size: 17px;
    display: flex;
    margin: 10px 4px 10px 0;
    align-items: center;
    justify-content: center;
    border-right: 2px solid #c8d4e6;
    border-radius: 1px;
    padding-right: 15px;
    .name {
      position: relative;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 600;
      color: #000000;
      line-height: 20px;
      letter-spacing: 5px;
    }
    .name::before {
      content: "";
      z-index: -1;
      position: absolute;
      bottom: 0px;
      left: 50%;
      width: 32px;
      height: 10px;
      border-radius: 50% / 100% 100% 0 0;
      width: 32px;
      height: 8px;
      background: linear-gradient(180deg, #0b6eff 0%, #eff3f9 100%);
      transform: skewX(180deg) translateX(-55%) translateY(50%);
      // clip-path: polygon(0 100%, 50% 0, 100% 100%);
    }
  }
  .topSelectList {
    flex: 1;
    display: flex;
    // align-items: center;
    // justify-content: center;
    flex-wrap: wrap;
    position: relative;
    .topSelectContainer {
      display: flex;
      flex-wrap: wrap;
      padding-left: 29px;
      .topSelectItem {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 15px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #555555;
        // line-height: 28px;
        cursor: pointer;
        height: 30px;
        border-radius: 4px;
        padding: 4px 8px;
        margin-right: 24px;
        margin-left: 0px;
        margin-bottom: 2px;
      }
      .topHasSelected {
        background: #cadfff;
        border-radius: 3px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #0b6eff;
        line-height: 14px;
        padding: 2px 8px;
      }
    }
    .selectAll {
      position: absolute;
      color: #606266;
      font-size: 14px;
      padding: 0;
      width: 50px;
      height: 20px;
      line-height: 20px;
      text-align: center;
      background: #e2f3ff;
      cursor: pointer;
    }
    .topSelectMore {
      // width: 60px;
      height: 26px;
      display: flex;
      align-items: center;
      margin: 0 20px;
      position: absolute;
      right: -70px;
      font-size: 14px;
      top: 5px;
      button {
        padding: 3px 5px;
        display: flex;
        justify-content: center;
        align-items: center;
        border: none;
        color: #555555;
        background: #f1f1f1;
        cursor: pointer;
      }
      i {
        font-size: 5px;
        margin-left: 6px;
      }
    }
  }
}
// 最外面的容器的代码在index.scss中
.tooltipWrapper {
  width: 669px;
  // height: 384px;
  // box-shadow: 0px 0px 26px 0px rgba(178, 181, 203, 0.5);
  // border-radius: 8px;
  .tooltipTop {
    display: flex;
    align-items: center;
    // height: 49px;
    padding-top: 2px;
    padding-bottom: 12px;
    font-size: 18px;
    font-family: PingFang-SC-Bold, PingFang-SC;
    font-weight: bold;
    color: #222222;
    line-height: 25px;
    border-bottom: 1px solid #c8d4e6;
    padding-left: 16px;
  }
  .tooltipContent {
    display: flex;
    .secondCategory {
      flex: 0.1 0.1 179px;
      padding-top: 12px;
      min-height: 276px;
      max-height: 276px;
      overflow-y: scroll;
      overflow-x: hidden;
      border-right: 1px solid #c8d4e6;
      .secondCategoryItem {
        cursor: pointer;
        display: flex;
        align-items: center;
        width: 179px;
        height: 32px;
        padding-left: 18px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #555555;
        line-height: 20px;
        &:hover {
          background: #ecf4ff;
        }
        &.active {
          color: #0b6eff;
        }
      }
      .secondHasSelected {
        color: #0b6eff;
      }
      &::-webkit-scrollbar {
        width: 4px;
        background-color: #fff;
        border-radius: 4px;
      }
      &::-webkit-scrollbar-thumb {
        background-color: #d8d8d8;
        border-radius: 4px;
      }
    }
    .thirdCategory {
      flex: 1 1 486px;
      padding: 21px 18px;
      max-height: 276px;

      min-height: 276px;
      overflow-y: scroll;
      overflow-x: hidden;
      .thirdCategoryItem {
        .thirdCategoryItemTitle {
          display: flex;
          align-items: center;
          font-size: 16px;
          font-family: PingFang-SC-Bold, PingFang-SC;
          font-weight: bold;
          color: #555555;
          margin-bottom: 15px;
          &::before {
            display: flex;
            content: "";
            width: 3px;
            height: 13px;
            background: #0b6eff;
            border-radius: 2px;
            margin-right: 10px;
          }
        }
        .thirdCategoryItemContent {
          ::v-deep.el-checkbox {
            line-height: 36px;
          }
        }
      }
      &::-webkit-scrollbar {
        width: 4px;
        background-color: #fff;
        border-radius: 4px;
      }
      &::-webkit-scrollbar-thumb {
        background-color: #d8d8d8;
        border-radius: 4px;
      }
    }
  }
  .tooltipBottom {
    display: flex;
    align-items: center;
    // height: 56px;
    padding: 18px 16px 5px 16px;
    font-size: 15px;
    font-family: PingFang-SC-Bold, PingFang-SC;
    font-weight: bold;
    color: #222222;
    // line-height: 21px;
    padding-left: 16px;
    border-top: 1px solid #c8d4e6;
    .tooltipBottonLabel {
      width: 85px;
      height: 21px;
      font-size: 15px;
      font-family: PingFang-SC-Bold, PingFang-SC;
      font-weight: bold;
      color: #222222;
      line-height: 21px;
    }
    .tooltipBottonTag {
      display: flex;
      align-items: center;
      margin-right: 16px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #0d6ffe;
      height: 26px;
      padding: 3px 8px;
      &:last-of-type {
        margin-right: 0px;
      }
      ::v-deep.el-icon-close {
        top: 1px;
      }
    }
  }
}
.tooltipWrapper ~ .popper__arrow {
  border-color: white;
}
::v-deep .el-checkbox {
  font-weight: 400;
  .el-checkbox__inner {
    width: 12px;
    height: 12px;
    border-radius: 3px;
  }
  .el-checkbox__input.is-checked .el-checkbox__inner,
  .el-checkbox__input.is-indeterminate .el-checkbox__inner {
    background-color: #fff;
  }
  .el-checkbox__inner::after {
    left: 3px;
    height: 5px;
    width: 3px;
    border: 1px solid #0b6eff;
    border-left: 0;
    border-top: 0;
  }
}
</style>
